<?php


namespace app\api\model\v2;

use app\api\model\dealer\Setting;
use app\common\model\dealer\User as DealerUserModel;

class DealerUser extends DealerUserModel
{
    /**
     * 创建分销关系
     * @param $user_id
     * @param $referee_id
     * @return bool
     */
    public static function createRelation($user_id, $referee_id)
    {
        // 分销商基本设置
        $setting = Setting::getItem('basic');
        // 是否开启分销功能
        if (!$setting['is_open']) {
            return false;
        }
        // 自分享
        if ($user_id == $referee_id) {
            return false;
        }
        //判断用户是否已绑定关系
        if (static::getByUserID($user_id)) {
            return false;
        }
        //判断推荐用户是否分销商
        if (!static::getByUserID($referee_id)) {
            return false;
        }
        //绑定关系
        self::addUser($user_id, $referee_id);
        return true;
    }

    /**
     * 上级分销商信息
     */
    public static function getByRefereeId($referee_id)
    {
        return self::where('referee_id', $referee_id)->where('is_delete', 0)->find();
    }

    /**
     * 获取分销成员数量
     */
    public static function getLevelNum($referee_id)
    {
        return self::where('referee_id', $referee_id)->where('is_delete', 0)->count();
    }

    /**
     * 获取上级分销商id
     */
    public static function getRefereeId($user_id)
    {
        return self::where('user_id', $user_id)->where('is_delete', 0)->value('referee_id');
    }

    /**
     * 新增关系
     */
    public static function addUser($user_id, $referee_id)
    {
        return self::create([
            'user_id' => $user_id,
            'referee_id' => $referee_id,
            'wxapp_id' => static::$wxapp_id,
            'create_time' => time(),
            'update_time' => time()
        ]);
    }

    /**
     * 累计分销商成员数量
     * @param $dealer_id
     * @param $level
     * @return int|true
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function setMemberInc($referee_id, $level)
    {
        $fields = [1 => 'first_num', 2 => 'second_num', 3 => 'third_num'];
        $model = self::getByUserID($referee_id);
        return $model->setInc($fields[$level]);
    }

    /**
     * 销售业绩
     */
    public static function setExpendMoneyInc($user_id, $money)
    {
        return self::where("user_id", $user_id)->setInc("expend_money", $money);
    }

}